package com.freedom.auth.domain.service.user;

import cn.hutool.core.lang.Assert;
import com.freedom.admin.api.feign.UserFeign;
import com.freedom.admin.api.pojo.dto.UserAuthDTO;
import com.freedom.common.core.enums.AuthResultCodeEnum;
import com.freedom.common.core.result.CommonResult;
import com.freedom.common.framework.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 系统用户体系业务类
 *
 */
@Service("sysUserDetailsService")
@Slf4j
@RequiredArgsConstructor
public class SysUserDetailsServiceImpl implements UserDetailsService {

    private final UserFeign userFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        CommonResult<UserAuthDTO> result = userFeign.findUserByUsername(username);
        Assert.isTrue(CommonResult.isSuccess(result), () -> new ServiceException(AuthResultCodeEnum.ACCOUNT_NOT_EXIST));

        SysUserDetails userDetails = new SysUserDetails(result.getData());

        Assert.isTrue(userDetails.isEnabled(), () -> new ServiceException(AuthResultCodeEnum.ACCOUNT_LOCKED));
        Assert.isTrue(userDetails.isAccountNonLocked(), () -> new ServiceException(AuthResultCodeEnum.ACCOUNT_LOCKED));
        Assert.isTrue(userDetails.isAccountNonExpired(), () -> new ServiceException(AuthResultCodeEnum.ACCOUNT_TIME_OUT));

        return userDetails;
    }

}
